<template>
  <el-dialog v-model="dialogVisible" title="举报" width="500px" destroy-on-close :close-on-click-modal="false"
    @close="handleClose" append-to-body>
    <el-form ref="reportFormRef" :model="reportForm" :rules="reportRules" label-width="100px">
      <el-form-item label="举报类型" prop="reportType" v-if="!type">
        <el-select v-model="reportForm.reportType" placeholder="请选择举报类型" style="width: 100%">
          <el-option label="垃圾广告" :value="1" />
          <el-option label="违法违规" :value="2" />
          <el-option label="色情低俗" :value="3" />
          <el-option label="恶意攻击" :value="4" />
          <el-option label="其他" :value="5" />
        </el-select>
      </el-form-item>

      <el-form-item label="违规类型" prop="violationType" v-else>
        <el-select v-model="reportForm.violationType" placeholder="请选择违规类型" style="width: 100%">
          <el-option label="政治敏感" value="政治敏感" />
          <el-option label="暴力内容" value="暴力内容" />
          <el-option label="色情内容" value="色情内容" />
          <el-option label="虚假信息" value="虚假信息" />
          <el-option label="恶意广告" value="恶意广告" />
          <el-option label="其他违规" value="其他违规" />
        </el-select>
      </el-form-item>

      <el-form-item label="举报原因" prop="reason">
        <el-input v-model="reportForm.reason" type="textarea" :rows="4" placeholder="请详细描述举报原因" maxlength="200"
          show-word-limit />
      </el-form-item>
      <el-form-item label="上传证据">
        <div class="evidence-container">
          <!-- 已上传的图片显示 -->
          <div v-if="reportForm.evidence" class="evidence-preview">
            <img :src="reportForm.evidence" alt="证据图片" class="evidence-image" />
            <div class="evidence-actions">
              <el-button type="danger" size="small" circle @click="handleImageRemove" title="删除图片">
                <el-icon>
                  <Close />
                </el-icon>
              </el-button>
            </div>
          </div>

          <!-- 上传组件 -->
          <el-upload v-else class="report-upload" :action="`${FILE_URL}/app/common/upload`" list-type="picture-card"
            :auto-upload="true" :on-success="handleUploadSuccess" :on-error="handleUploadError"
            :on-change="handleImageChange" :limit="1" accept="image/jpeg,image/png" name="Image"
            :show-file-list="false">
            <template #default>
              <el-icon>
                <Plus />
              </el-icon>
            </template>
          </el-upload>
        </div>
        <div class="upload-tip">支持jpg、png格式，单张不超过5MB</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitReport" :loading="submitting"> 提交举报 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import { postReportQuestion, postReportAnswer, postReportaddReport } from '@/axios/api/question'

// 获取host.js中的FILE_URL
const FILE_URL = window.hosts.FILE_URL[import.meta.env.MODE]

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  // 被举报内容的相关信息
  reportInfo: {
    type: Object,
    default: () => ({}),
  },
  type: {
    // type: Number,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(props.modelValue)
const submitting = ref(false)
const reportFormRef = ref(null)




// 监听modelValue的变化
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val
  },
)

// 监听dialogVisible的变化
watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:modelValue', val)
  },
)

const reportForm = reactive({
  reportType: '',
  violationType:'',
  reason: '',
  evidence: '', // 图片地址，多个图片用逗号分隔
})

const reportRules = {
  reportType: [{ required: true, message: '请选择举报类型', trigger: 'change' }],
  violationType:[{ required: true, message: '请选择违规类型', trigger: 'change' }],
  reason: [
    { required: true, message: '请填写举报原因', trigger: 'blur' },
    { min: 5, message: '举报原因至少5个字符', trigger: 'blur' },
  ],
}

// 处理图片上传成功
function handleUploadSuccess(response) {
  if (response.code === 0) {
    const imageUrl = response.result
    // 直接设置图片URL到evidence中（只支持1张图片）
    reportForm.evidence = imageUrl
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败：' + response.msg)
  }
}

// 处理图片上传失败
function handleUploadError() {
  ElMessage.error('图片上传失败，请重试')
}

// 处理图片选择
function handleImageChange(file) {
  if (!['image/jpeg', 'image/png'].includes(file.raw?.type)) {
    ElMessage.error('只能上传JPG或PNG格式的图片！')
    return false
  }
  if (file.size / 1024 / 1024 > 5) {
    ElMessage.error('图片大小不能超过5MB！')
    return false
  }
  return true
}

// 处理图片删除
function handleImageRemove() {
  reportForm.evidence = ''
  ElMessage.success('图片已删除')
}

function handleClose() {
  dialogVisible.value = false
  reportFormRef.value?.resetFields()
  reportForm.evidence = ''
}

async function submitReport() {
  if (!reportFormRef.value) return

  try {
    await reportFormRef.value.validate()
    submitting.value = true

    // 构建请求参数
    const reportData = {
      reportType: parseInt(reportForm.reportType),
      reason: reportForm.reason.trim(),
      evidence: reportForm.evidence || '',
      questionId: props.reportInfo.type === 'question' ? props.reportInfo.id : 0,
      answerId: props.reportInfo.type === 'answer' ? props.reportInfo.id : 0,
      violationType:reportForm.violationType
    }

    // 根据举报类型调用不同的接口
    let response
    if (props.type) {
      let obj = {
        cateId: props.type,
        media: [reportData.evidence],
        content: reportData.reason,
        linkId: props.reportInfo.id,
        violationType: reportData.violationType
      }

      console.log(obj);
      response = await postReportaddReport(obj)
    } else {
      if (props.reportInfo.type === 'question') {
        response = await postReportQuestion(reportData)
      } else {
        response = await postReportAnswer(reportData)
      }
    }

    if (response.code === 0) {
      ElMessage.success('举报提交成功')
      emit('success', reportData)
      handleClose()
    } else {
      ElMessage.error(response.msg || '举报提交失败')
    }
  } catch (error) {
    console.error('举报提交失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.report-upload {
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
    position: relative;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item-actions) {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item:hover .el-upload-list__item-actions) {
    opacity: 1;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item-actions .el-icon) {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
  }
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-text {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.evidence-container {
  display: flex;
  align-items: flex-start;
}

.evidence-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.evidence-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.evidence-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  z-index: 10;
}

.evidence-actions .el-button {
  width: 24px;
  height: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.evidence-actions .el-icon {
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
